import requests


class Prometheus:

    ReadyPath = '/-/ready'
    QueryPath = '/api/v1/query'
    LabelPath = '/api/v1/label/__name__/values'

    def __init__(self, **kwargs):
        self.base_url = None
        self.auth = None
        if kwargs:
            self.init(**kwargs)

    def init_from_params(self, scheme, ip, port, path, auth=None):
        self.base_url = f'{scheme.strip()}{ip}:{port}/{path.strip().lstrip("/")}'
        self.auth = auth

    def init(self, base_url='', auth=None):
        self.base_url = base_url.strip('/')
        self.auth = auth

    def is_ready(self):
        resp = requests.request('GET', f'{self.base_url}{self.ReadyPath}')
        if resp.text.strip() == 'Prometheus is Ready.':
            return True
        return False

    def labels(self, **kwargs):
        resp = requests.request('GET', f'{self.base_url}{self.LabelPath}', **kwargs)
        return resp.json()

    def query(self, **kwargs):
        resp = requests.request('GET', f'{self.base_url}{self.QueryPath}', **kwargs)
        return resp.json()

    def custom(self, path, **kwargs):
        """自定义 任意promethus请求皆可支持"""
        resp = requests.request(url=f'{self.base_url}{path}', **kwargs)
        return resp.json()


prometheus = Prometheus()


if __name__ == '__main__':
    prometheus.init(base_url='http://192.168.101.79:3090')

    response = prometheus.is_ready()
    print(response)

    response = prometheus.labels()
    print(response)

    response = prometheus.query(params={'query': 'node_network_iface_id{device="cni0"}'})
    print(response)
